/*
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package logmatcher.buffers;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import logmatcher.InputFilter;
import logmatcher.LogEventBuffer;
import logmatcher.LogEventListener;

import org.apache.commons.collections.Buffer;
import org.apache.commons.collections.buffer.UnboundedFifoBuffer;
import org.apache.commons.lang.NotImplementedException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 *  Implementation of LogBuffer. Forces using input filters. Each filter maintains its own list of message
 *  listeners. When filter accepts a message then all listeners are notified. All filters are checked while handling a
 *  message.
 *
 *  @version $Rev: 417 $
 */
public class FilterPriorityBuffer implements LogEventBuffer {
    //~ Static fields/initializers -------------------------------------------------------------------------------------

    /** Class logger. */
    private static final Log LOGGER = LogFactory.getLog(FilterPriorityBuffer.class);

    //~ Instance fields ------------------------------------------------------------------------------------------------

    /** Buffer for messages. */
    private Buffer messageBuffer;

    /** Map between filters and their listeners. */
    private Map<InputFilter, List<LogEventListener>> filters;

    //~ Constructors ---------------------------------------------------------------------------------------------------

/**
     *  Creates a new FilterPriorityBuffer object.
    */
    public FilterPriorityBuffer() {
        messageBuffer = new UnboundedFifoBuffer();
        filters = new HashMap<InputFilter, List<LogEventListener>>();
    }

    //~ Methods --------------------------------------------------------------------------------------------------------

    /**
     *  Adds a message to the buffer.
     *
     *  @param message message to be added.
     */
    public void receiveLogEvent(Object message) {
        messageBuffer.add(message);

        //is it good time to call this here?       
        if (filters.size() > 0) {
            processMessage(message);
        }
    }


    /**
     *  {@inheritDoc}
     */
    public void addLogEventListener(LogEventListener listener, InputFilter filter) {
        if (filters.containsKey(filter)) {
            //if filter is installed then just add new listener
            filters.get(filter).add(listener);
        } else {
            //otherwise put filter and a new list of listeners into the map
            List<LogEventListener> listeners = new ArrayList<LogEventListener>();
            listeners.add(listener);
            filters.put(filter, listeners);
        }
    }


    /**
     *  {@inheritDoc}
     */
    public void addLogEventListener(LogEventListener listener) {
        throw new NotImplementedException("This implementation of LogBuffer disables using this method.");
    }


    /**
     *  Processes messages.
     *
     *  @param message message to be processed.
     */
    private void processMessage(Object message) {
        Set<InputFilter> fs = filters.keySet();

        for (InputFilter f : fs) {
            if (f.accept(message)) {
                notifyAllSubscribers(f, message);
            }
        }
    }


    /**
     *  Notifies all message listeners connected to the input filter.
     *
     *  @param filter filter
     *  @param message message listeners connected to the filter
     */
    private void notifyAllSubscribers(InputFilter filter, Object message) {
        List<LogEventListener> listeners = filters.get(filter);

        for (LogEventListener listener : listeners) {
            listener.receiveLogEvent(message);
        }
    }
}
